package group.sicher.core.encrypt.impl;

import group.sicher.core.encrypt.EncryptService;
import group.sicher.core.encrypt.exception.EncryptConfigException;
import group.sicher.core.encrypt.exception.EncryptException;
import group.sicher.core.utils.AesUtil;
import lombok.Setter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author Donald
 * @description Aes加密
 * @date 2019-07-02
 **/
@Service("aesService")
@Setter
@PropertySource(value = "classpath:application_core.properties", encoding = "UTF-8")
@ConfigurationProperties(prefix = "encrypt.aes", ignoreInvalidFields = true)
public class AesEncryptServiceImpl implements InitializingBean, EncryptService {
    private String key;
    private String iv;

    @Override
    public void afterPropertiesSet() throws Exception {
        if (StringUtils.isEmpty(key)) {
            throw new EncryptConfigException("Aes配置失败: Key不能为空");
        }

        if (StringUtils.isEmpty(iv)) {
            throw new EncryptConfigException("Aes配置失败: IV不能为空");
        }
    }

    @Override
    public String encrypt(String origin) throws EncryptException {
        try {
            return AesUtil.encrypt(origin, key, iv);
        } catch (Exception e) {
            throw new EncryptException("Aes加密失败：" + e.getMessage());
        }
    }

    @Override
    public String decrypt(String cipher) throws EncryptException {
        try {
            return AesUtil.decrypt(cipher, key, iv);
        } catch (Exception e) {
            throw new EncryptException("Aes加密失败：" + e.getMessage());
        }
    }
}
